package com.dongdongshop.controller;

import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.SmsService;
import com.dongdongshop.service.UserService;
import com.dongdongshop.util.Result;
import com.dongdongshop.util.ShiroUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping("user")
public class UserController {

    @DubboReference
    private UserService userService;

    @DubboReference
    private SmsService smsService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("show")
    public String show() {
        return "register";
    }


    @RequestMapping("sendPhone")
    @ResponseBody
    public Result sendPhone(String phone) {
        smsService.sendPhone(phone);
        return Result.OK();
    }

    @RequestMapping("register")
    @ResponseBody
    public Result userAdd(TbUser user, String code) {
        String code1 = stringRedisTemplate.boundValueOps(user.getPhone()).get();
        if (!code1.equals(code)) {
            return Result.response(ResultEnum.PARAMETER_FAILE);
        }
        //将手机放到redis中
        stringRedisTemplate.opsForValue().get(user.getPhone());
        try {
            ShiroUtils shiroUtils = new ShiroUtils();
            //使用加盐的方法获取一个新值
            String s = shiroUtils.saltPassword(user.getPassword());
            //截取
            String[] split = s.split(",");
            //给审核默认为Y
            user.setStatus("Y");
            user.setPassword(split[1]);
            user.setSalt(split[0]);
            user.setCreated(new Date());
            user.setUpdated(new Date());
            userService.insert(user);
            return Result.response(ResultEnum.ENROLL_SUCCESS);
        } catch (Exception e) {
            return Result.response(ResultEnum.ENROLL_ERROR);
        }
    }
}
